﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using ThoughtWorks.QRCode.Codec;

namespace Xproject.Util
{
    public   class QRcodeHelper
    {
                
        private static int ImageSize = 10;
        public static string  Create_CodeImages(string Contents,string FilePath,string FileName)
        {
            try
            {
                //生成图片  
                Bitmap image = Create_ImgCode(Contents, ImageSize);
                if (File.Exists(FilePath + FileName))
                {
                    return FilePath + FileName;
                }
                //保存图片  
              return  SaveImg(FilePath,FileName, image);
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
        /// <summary>  
        /// 保存图片  
        /// </summary>  
        /// <param name="strPath">保存路径</param>  
        /// <param name="img">图片</param>  
        private  static string  SaveImg(string strPath,string FileName, Bitmap img)
        {
            //保存图片到目录  
            if (!Directory.Exists(strPath))           
            {
                //当前目录不存在，则创建  
                Directory.CreateDirectory(strPath);
                img.Save(strPath + "/" + FileName, ImageFormat.Png);
            }
            img.Save(strPath + "/" + FileName, ImageFormat.Png);
            return strPath + "/" + FileName;
        }
        /// <summary>  
        /// 生成二维码图片  
        /// </summary>  
        /// <param name="codeNumber">要生成二维码的字符串</param>       
        /// <param name="size">大小尺寸</param>  
        /// <returns>二维码图片</returns>  
        private  static Bitmap Create_ImgCode(string cotent, int size)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            //设置编码模式  
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            //设置编码测量度  
            qrCodeEncoder.QRCodeScale = size;             
            //设置编码版本  
            qrCodeEncoder.QRCodeVersion = 0;
            //设置编码错误纠正  
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            //生成二维码图片  
            System.Drawing.Bitmap image = qrCodeEncoder.Encode(cotent);
            return image;
        }                               

        /// <summary>  
        /// /打开指定目录  
        /// </summary>  
        /// <param name="path"></param>  
        private  static void Open_File(string path)
        {
            System.Diagnostics.Process.Start("explorer.exe", path);
        }
        /// <summary>  
        /// 删除目录下所有文件  
        /// </summary>  
        /// <param name="aimPath">路径</param>  
        private static void DeleteDir(string aimPath)
        {
            try
            {
                //目录是否存在  
                if (Directory.Exists(aimPath))
                {
                    // 检查目标目录是否以目录分割字符结束如果不是则添加之  
                    if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                        aimPath += Path.DirectorySeparatorChar;
                    // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组  
                    // 如果你指向Delete目标文件下面的文件而不包含目录请使用下面的方法  
                    string[] fileList = Directory.GetFiles(aimPath);
                    //string[] fileList = Directory.GetFileSystemEntries(aimPath);  
                    // 遍历所有的文件和目录  
                    foreach (string file in fileList)
                    {
                        // 先当作目录处理如果存在这个目录就递归Delete该目录下面的文件  
                        if (Directory.Exists(file))
                        {
                            DeleteDir(aimPath + Path.GetFileName(file));
                        }
                        // 否则直接Delete文件  
                        else
                        {
                            File.Delete(aimPath + Path.GetFileName(file));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }


        /// <summary>
        /// 创建一张带有背景的二维码图
        /// </summary>
        /// <param name="Contents"></param>
        /// <param name="FilePath"></param>
        /// <param name="FileName"></param>
        /// <param name="backgroundImg"></param>
        /// <returns></returns>
        public static void  Create_CodeImagesWithBackground(string Contents, string FilePath, string FileName,string backgroundImg)
        {
            if (!File.Exists(FilePath + FileName))
            {                             
                //先得到背景图
                Bitmap imageBackGround = new Bitmap(backgroundImg);
                try
                {
                    //生成二维码图片  
                    Bitmap image = Create_ImgCode(Contents, ImageSize);
                    imageBackGround =  CombinImage(imageBackGround, image, 53, 152);               
                    //保存图片  
                      SaveImg(FilePath, FileName, imageBackGround);
                }
                catch (Exception ex)
                {                
                }
            }
        }

        public static void CreateProductTuiGuangQRcode(string urlcontent,string productImgaddress,string productName, string productDesc,string price,string orginprice, string FilePath, string FileName)
        {
            
            Bitmap b1 = new Bitmap(640, 880); //新建位图b1
            Graphics g1 = Graphics.FromImage(b1); //创建b1的Graphics
            g1.FillRectangle(Brushes.White, new Rectangle(0, 0, 640, 880)); //把b1涂成红色                       
            String str = "长按图片识别上方二维码";
            Font font15 = new Font("宋体", 15);
            Font font25 = new Font("宋体", 25);
            Font font19 = new Font("宋体", 19,FontStyle.Bold);
            Font font17 = new Font("宋体", 17);
            Font font28 = new Font("宋体", 28);
            SolidBrush redbrush = new SolidBrush(Color.Red);
            SolidBrush blackbrush = new SolidBrush(Color.Black);
            SolidBrush graybrush = new SolidBrush(Color.Gray);

            
            Brush fontBrush = SystemBrushes.ControlText;            
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Near;
            sf.LineAlignment = StringAlignment.Near;
            RectangleF namerec = new RectangleF(10, 600, 350, 85);
            RectangleF descrec = new RectangleF(10, 690, 350, 90);
            g1.DrawString(productName, font19, fontBrush, namerec, sf);
            g1.DrawString(productDesc, font17, fontBrush, descrec, sf);
            // g1.DrawString(productName, font19, blackbrush, new PointF(10, 600));
            g1.DrawString(str, font15, redbrush, new PointF(385, 855));
            
            g1.DrawString("现价:￥" + price, font28, redbrush,new PointF(10,790));
            g1.DrawString("原价:￥" + orginprice, font15, graybrush, new PointF(10, 850));
            g1.DrawLine(new Pen(Color.Red, 2), 10, 856,140, 858);
            Bitmap qrcode = Create_ImgCode(urlcontent, ImageSize);           
            g1.DrawImage(qrcode, 380, 600, 240, 240);
            string Virbase = @"Upload\Images\Sales\";
            string tFolder = "template";
            string localpath = AppDomain.CurrentDomain.BaseDirectory + Virbase;
            string Folder = localpath + tFolder;
            if (!Directory.Exists(Folder))
                Directory.CreateDirectory(Folder);
            string FileFullName = Folder + "\\" + Guid.NewGuid().ToString() + ".jpg";
            SavePhotoFromUrl(FileFullName, productImgaddress);
            Bitmap product  = new Bitmap(FileFullName);
            g1.DrawImage(product, 10, 10, 620, 580);
            SaveImg(FilePath, FileName, b1);
        }
        /// <summary>  
        /// 合并图片  
        /// </summary>  
        /// <param name="imgBack"></param>  
        /// <param name="img"></param>  
        /// <returns></returns>  
        private  static Bitmap CombinImage(Image imgBack, Image img, int xDeviation = 0, int yDeviation = 0)
        {

            Bitmap bmp = new Bitmap(imgBack.Width, imgBack.Height );

            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);             

            g.DrawImage(img, xDeviation, yDeviation, img.Width, img.Height);
            GC.Collect();
            return bmp;
        }

        public static bool SavePhotoFromUrl(string FileName, string Url)
        {
            bool Value = false;
            WebResponse response = null;
            Stream stream = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

                response = request.GetResponse();
                stream = response.GetResponseStream();

                if (!response.ContentType.ToLower().StartsWith("text/"))
                {
                    Value = SaveBinaryFile(response, FileName);

                }

            }
            catch (Exception err)
            {
                string aa = err.ToString();
            }
            return Value;
        }
        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool Value = true;
            byte[] buffer = new byte[1024];

            try
            {
                if (File.Exists(FileName))
                    File.Delete(FileName);
                Stream outStream = System.IO.File.Create(FileName);
                Stream inStream = response.GetResponseStream();

                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0)
                        outStream.Write(buffer, 0, l);
                }
                while (l > 0);

                outStream.Close();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }
    }
}
